package pl.mchaniewski.ryneczek.web.user;

import javax.faces.application.FacesMessage;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.User;
import pl.mchaniewski.ryneczek.services.UserService;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.utilities.SecurityUtil;
import pl.mchaniewski.ryneczek.web.FormButton;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class ChangePasswordBean extends FormButton {
    private UserService userService;

    /* Form */
    @Size(min = 5, max = 30, message = "{changepasswordbean.passwordSize}")
    private String pass1;
    @Size(min = 5, max = 30, message = "{changepasswordbean.passwordSize}")
    private String pass2;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getPass1() {
        return pass1;
    }

    public void setPass1(String pass1) {
        this.pass1 = pass1;
    }

    public String getPass2() {
        return pass2;
    }

    public void setPass2(String pass2) {
        this.pass2 = pass2;
    }

    public String save() {
        if (!getPass1().equals(getPass2())) {
            FacesMessageUtil.addMessage(getButton(), I18nUtil
                    .getLocalizedMessage("changepasswordbean.doesntMatch"),
                    FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.SAME_PAGE;
        }

        UserDetails secUser = SecurityUtil.getUserDetails();
        if (secUser == null) {
            return NavigationUtil.facesRedirectTo(NavigationUtil.INDEX);
        }

        User user = userService.findByLogin(secUser.getUsername());
        if (user == null) {
            return NavigationUtil.facesRedirectTo(NavigationUtil.INDEX);
        } else {

            if (userService.changePassword(user, getPass1()) != null) {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("changepasswordbean.success"),
                        FacesMessage.SEVERITY_INFO);
            } else {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("changepasswordbean.notSuccess"),
                        FacesMessage.SEVERITY_WARN);
            }

        }

        return NavigationUtil.SAME_PAGE;
    }

}
